// 游戏状态
const gameStates = {
    WAITING: 'waiting',   // 等待开始
    READY: 'ready',       // 准备阶段
    GO: 'go',             // 点击阶段
    TOO_SOON: 'too-soon'  // 过早点击
};

// 游戏元素
const gameArea = document.getElementById('game-area');
const gameMessage = document.getElementById('game-message');
const resultDisplay = document.getElementById('result');
const resultContainer = document.getElementById('result-container');
const feedback = document.getElementById('feedback');
const bestTimeDisplay = document.getElementById('best-time');
const averageTimeDisplay = document.getElementById('average-time');
const attemptsDisplay = document.getElementById('attempts');
const resetBtn = document.getElementById('reset-btn');

// 游戏变量
let currentState = gameStates.WAITING;
let startTime;
let timeoutId;
let results = [];

// 初始化游戏
function initializeGame() {
    // 从本地存储加载数据
    loadStats();
    updateStats();
    
    // 如果有保存的结果，显示重置按钮
    if (results.length > 0) {
        resetBtn.classList.remove('hidden');
    }
    
    // 设置游戏区域点击事件
    gameArea.addEventListener('click', handleGameAreaClick);
    
    // 设置重置按钮点击事件
    resetBtn.addEventListener('click', resetStats);
}

// 处理游戏区域点击
function handleGameAreaClick() {
    switch(currentState) {
        case gameStates.WAITING:
            startGame();
            break;
        case gameStates.READY:
            tooSoon();
            break;
        case gameStates.GO:
            stopGame();
            break;
        case gameStates.TOO_SOON:
            resetGameArea();
            break;
    }
}

// 开始游戏
function startGame() {
    currentState = gameStates.READY;
    gameArea.className = 'game-area ready';
    gameMessage.textContent = '准备...';
    resultContainer.classList.add('hidden');
    
    // 随机等待时间 (2-6秒)
    const randomDelay = Math.floor(Math.random() * 4000) + 2000;
    
    timeoutId = setTimeout(() => {
        currentState = gameStates.GO;
        gameArea.className = 'game-area go';
        gameMessage.textContent = '点击！';
        startTime = Date.now();
    }, randomDelay);
}

// 过早点击
function tooSoon() {
    clearTimeout(timeoutId);
    currentState = gameStates.TOO_SOON;
    gameArea.className = 'game-area too-soon';
    gameMessage.textContent = '太早了！点击重试';
}

// 停止游戏并显示结果
function stopGame() {
    const endTime = Date.now();
    const reactionTime = endTime - startTime;
    
    // 存储结果
    results.push(reactionTime);
    saveStats();
    
    // 更新统计信息
    updateStats();
    
    // 显示结果
    resultDisplay.textContent = reactionTime;
    resultContainer.classList.remove('hidden');
    
    // 提供反馈
    provideFeedback(reactionTime);
    
    // 显示重置按钮
    resetBtn.classList.remove('hidden');
    
    // 重置游戏区域
    // 延迟重置游戏区域，确保反馈有时间显示
    setTimeout(() => {
        resetGameArea();
    }, 1000); // 延迟1秒后重置游戏区域
}

// 根据反应时间提供反馈
function provideFeedback(time) {
    if (time < 200) {
        feedback.textContent = '不可思议！超人般的反应！';
        feedback.style.color = '#9b59b6';
    } else if (time < 250) {
        feedback.textContent = '太棒了！专业选手级别！';
        feedback.style.color = '#2ecc71';
    } else if (time < 300) {
        feedback.textContent = '非常好！反应超快！';
        feedback.style.color = '#27ae60';
    } else if (time < 350) {
        feedback.textContent = '很好！高于平均水平！';
        feedback.style.color = '#d7eaf6';
    } else if (time < 400) {
        feedback.textContent = '不错！接近平均水平';
        feedback.style.color = '#3498db';
    } else if (time < 500) {
        feedback.textContent = '一般水平，还可以提高';
        feedback.style.color = '#e67e22';
    } else {
        feedback.textContent = '有点慢，多练习就会变快！';
        feedback.style.color = '#e74c3c';
    }
}

// 重置游戏区域
function resetGameArea() {
    currentState = gameStates.WAITING;
    gameArea.className = 'game-area waiting';
    gameMessage.textContent = '点击此处开始';

    // 不要隐藏结果容器，让用户可以继续看到上一次的结果
    // resultContainer.classList.add('hidden');
}

// 更新统计信息
function updateStats() {
    if (results.length > 0) {
        // 计算最佳时间
        const bestTime = Math.min(...results);
        bestTimeDisplay.textContent = bestTime;
        
        // 计算平均时间
        const sum = results.reduce((a, b) => a + b, 0);
        const average = Math.round(sum / results.length);
        averageTimeDisplay.textContent = average;
        
        // 更新尝试次数
        attemptsDisplay.textContent = results.length;
    }
}

// 重置统计信息
function resetStats() {
    results = [];
    saveStats();
    
    bestTimeDisplay.textContent = '-';
    averageTimeDisplay.textContent = '-';
    attemptsDisplay.textContent = '0';
    
    resetBtn.classList.add('hidden');
    resultContainer.classList.add('hidden');
}

// 保存统计信息到本地存储
function saveStats() {
    localStorage.setItem('reactionTimeResults', JSON.stringify(results));
}

// 从本地存储加载统计信息
function loadStats() {
    const savedResults = localStorage.getItem('reactionTimeResults');
    if (savedResults) {
        results = JSON.parse(savedResults);
    }
}

// 初始化游戏
document.addEventListener('DOMContentLoaded', initializeGame);